﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using Shuba.Model;

namespace Shuba.Web.master
{
    public partial class branch_nip_so_add : basePage
    {
        string msg = "";
        private void BindData()
        {
            hidID.Value = Request.QueryString["id"];

            Shuba.Business.BranchNipSOMap _BranchNipSOMap = new Shuba.Business.BranchNipSOMap();
            BranchNipSOMapInfo bi = _BranchNipSOMap.Get(hidID.Value.ToString());

            txtBranchCode.Text = bi.BRANCH_ID;
            txtAOCode.Text = bi.AO_CODE;
            txtNIP.Text = bi.NIP;
            txtHP.Text = bi.HP;
            hidOldMACAddress.Value = bi.MAC_ADDRESS;
            txtMACAddress.Text = bi.MAC_ADDRESS;
            ddlUserType.SelectedIndex = ddlUserType.Items.IndexOf(ddlUserType.Items.FindByValue(bi.USER_TYPE));
            chkIsMigration.Checked = bi.IS_MIGRATION == "1" ? true : false;
            ddlAOType.SelectedValue = bi.AO_TYPE;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.Form.DefaultFocus = txtBranchCode.ClientID;
            this.Form.DefaultButton = btnSubmit.UniqueID;

            if (!Page.IsPostBack)
            {
                BindUserTypeData();

                string acl = GetUserAccess("MSTR_BRANCH_NIP_SO_MAP");

                if (!IsUserAdd(acl) && !IsUserEdit(acl))
                {
                    msg = this.GetGlobalResourceObject("Messages", "NoPrivilege").ToString();
                    AlertAndRedirect(msg, ResolveUrl(ConfigurationManager.AppSettings["default_url"]));
                }

                LabelTitle.Text = GetPageTitle("MSTR_BRANCH_NIP_SO_MAP");

                RegVal1.ValidationExpression = "^[\\d\\s]+$";//"^[0-9\\s]+$";

                if (Request.QueryString["a"] == "ed")
                {
                    BindData();
                    txtNIP.Enabled = false;
                }
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {

            Shuba.Business.BranchNipSOMap blBranchNipSOMap = new Shuba.Business.BranchNipSOMap();
            BranchNipSOMapInfo bi = new BranchNipSOMapInfo();

            Shuba.Business.User blUser = new Shuba.Business.User();
            Shuba.Business.MsStd _MstStd = new Shuba.Business.MsStd();
            MstStdInfo mstInfo = _MstStd.Get(ddlUserType.SelectedValue, Int16.Parse(ddlAppType.SelectedValue));

            string UserType = ddlUserType.SelectedValue == null ? "" : ddlUserType.SelectedValue.Trim();

            bool IsValid = true;
            string ActType = "UPDATE", CurNIP;
            string SPAWEBAppCode = ConfigurationManager.AppSettings["app.code"];
            string SPADAAppCode = ConfigurationManager.AppSettings["app.code.spada"];
            string NipUM = "";

            if (ddlUserType.SelectedIndex == 0)
            {
                IsValid = false;
                msg = "Pilih User Type";
                Alert(msg);
            }

            if (ddlAOType.SelectedIndex == 0 && UserType == "SO")
            {
                IsValid = false;
                msg = "Pilih AO Capability";
                Alert(msg);
            }

            if (UserType == "UM")
            {
                NipUM = blBranchNipSOMap.GetUMByUnit(txtBranchCode.Text.Trim()).NIP + "";

                if (NipUM != "" && NipUM.Trim() != txtNIP.Text.Trim())
                {
                    IsValid = false;

                    msg = "Invalid Data, UM Is Already Registered in Unit [" + txtBranchCode.Text.Trim() + "]"; //this.GetGlobalResourceObject("Messages", "AppCodeExist").ToString();
                    Alert(msg);
                }
            }

            if (mstInfo.MstType.Trim() == "P")
            {
                Shuba.Business.HO ho = new Shuba.Business.HO();
                if (ho.Get(txtBranchCode.Text.Trim()).HO_ID == null)
                {
                    IsValid = false;

                    msg = "Invalid Cost Centre"; //this.GetGlobalResourceObject("Messages", "AppCodeExist").ToString();
                    Alert(msg);
                }
            }

            if (mstInfo.MstType.Trim() == "R")
            {
                Shuba.Business.Regional ho = new Shuba.Business.Regional();
                if (ho.Get(txtBranchCode.Text.Trim()).RegionalID == null)
                {
                    IsValid = false;

                    msg = "Invalid Cost Centre"; //this.GetGlobalResourceObject("Messages", "AppCodeExist").ToString();
                    Alert(msg);
                }
            }

            if (mstInfo.MstType.Trim() == "C")
            {
                Shuba.Business.Cluster ho = new Shuba.Business.Cluster();
                if (ho.Get(txtBranchCode.Text.Trim()).ClusterID == null)
                {
                    IsValid = false;

                    msg = "Invalid Cost Centre"; //this.GetGlobalResourceObject("Messages", "AppCodeExist").ToString();
                    Alert(msg);
                }
            }

            if (mstInfo.MstType.Trim() == "U")
            {
                Shuba.Business.Branch ho = new Shuba.Business.Branch();
                if (ho.Get(txtBranchCode.Text.Trim()).BranchID == null)
                {
                    IsValid = false;

                    msg = "Invalid Cost Centre"; //this.GetGlobalResourceObject("Messages", "AppCodeExist").ToString();
                    Alert(msg);
                }
            }
            txtMACAddress.Text = txtMACAddress.Text.Trim().Replace(":", "").Replace("-", "");
            if (UserType == "SO" && chkIsMigration.Checked && txtMACAddress.Text.Trim() == string.Empty) txtMACAddress.Text = hidOldMACAddress.Value;
            if (UserType == "SO" && txtMACAddress.Text.Trim() == string.Empty && !chkIsMigration.Checked && hidID.Value != "")
            {
                IsValid = false;

                msg = "MAC Address is Required"; //this.GetGlobalResourceObject("Messages", "AppCodeExist").ToString();
                Alert(msg);
            }

            if (IsValid && blUser.Get(txtNIP.Text.Trim(), SPAWEBAppCode).Name == null)
            {
                if (blUser.Get(txtNIP.Text.Trim(), SPADAAppCode).Name == null)
                {
                    bool checkHubSpoke = false;
                    if (blUser.GetHubSpokeUser(txtNIP.Text.Trim()) < 1 && ddlAppType.SelectedValue == "64")
                        checkHubSpoke = true;

                    if (ddlAppType.SelectedValue == "10" || checkHubSpoke)
                    {
                        IsValid = false;
                        msg = "Invalid NIP\\nPlease make sure NIP is correct and already registered in Application Management Console"; //this.GetGlobalResourceObject("Messages", "AppCodeExist").ToString();
                        Alert(msg);
                    }
                }
            }

            if (IsValid && txtAOCode.Text.Trim() != "-")
            {
                CurNIP = blBranchNipSOMap.GetByAOCode(txtAOCode.Text.Trim(), SPADAAppCode).NIP + "";
                if (CurNIP != "" && CurNIP.Trim() != txtNIP.Text.Trim())
                {
                    IsValid = false;

                    msg = "Invalid AO Code\\nAO Code is already registered in Database\\nPlease check your AO Code and make sure it is Unique"; //this.GetGlobalResourceObject("Messages", "AppCodeExist").ToString();
                    Alert(msg);
                }
            }


            #region UPDATE 14 Mei 2014
            /*
             * Penambahan validasi group id dengan ao capability
             * 
             */

            if (IsValid)
            {
                UserInfo ui = blUser.Get(txtNIP.Text.Trim(), SPADAAppCode);
                if (ui.Name != null)
                {
                    msg = "";
                    if (ddlAOType.SelectedValue == "L" && ui.GroupId != 10018)
                        msg = txtNIP.Text + " bukan dari Group Lending";
                    if (ddlAOType.SelectedValue == "F" && ui.GroupId != 10143)
                        msg = txtNIP.Text + " bukan dari Group Funding";
                    if (ddlAOType.SelectedValue == "FL" && ui.GroupId != 10144)
                        msg = txtNIP.Text + " bukan dari Group Funding Lending";

                    if (msg != "")
                    {
                        IsValid = false;
                        Alert(msg);
                    }
                }

            }
            #endregion

            if (!RequiredFieldValidator1.IsValid ||
                !RequiredFieldValidator3.IsValid || !RegVal1.IsValid)
            {
                IsValid = false;
                Alert("Please verify your entry");
            }

            if (IsValid)
            {
                if (hidID.Value == "")
                {
                    ActType = "INSERT";
                }

                bi.BRANCH_ID = txtBranchCode.Text.Trim();
                bi.AO_CODE = txtAOCode.Text.Trim();
                bi.NIP = txtNIP.Text.Trim();
                bi.USER_TYPE = UserType;
                bi.HP = txtHP.Text.Trim();
                bi.ENTRY_BY = HttpContext.Current.User.Identity.Name;
                bi.ENTRY_DATE = ProcessingDate();
                bi.UPDATE_BY = HttpContext.Current.User.Identity.Name;
                bi.UPDATE_DATE = ProcessingDate();
                bi.ACT_TYPE = ActType;
                bi.MAC_ADDRESS = chkIsMigration.Checked == true && ActType == "UPDATE" ? hidOldMACAddress.Value.Trim() : txtMACAddress.Text.Trim().Replace(":", "").Replace("-", "");
                //bi.MAC_ADDRESS = chkIsMigration.Checked == true && ActType == "UPDATE" ? "" : txtMACAddress.Text.Trim().Replace(":", "").Replace("-", "");
                bi.OLD_MAC_ADDRESS = hidOldMACAddress.Value.Trim();
                bi.IS_MIGRATION = chkIsMigration.Checked == true && hidID.Value != "" ? "1" : "0";
                bi.AO_TYPE = ddlAOType.SelectedValue;
                if (UserType != "SO")
                {
                    bi.MAC_ADDRESS = "";
                    bi.OLD_MAC_ADDRESS = "";
                    bi.IS_MIGRATION = "0";
                    bi.AO_TYPE = "";
                }

                try
                {
                    blBranchNipSOMap.Save(bi);

                    AddLog(ActType, ActType + " BRANCH NIP SO MAPPING");
                    msg = this.GetGlobalResourceObject("Messages", "SaveAlert").ToString();
                    AlertAndRedirect(msg, "branch_nip_so_list.aspx");
                }
                catch (Exception ex)
                {
                    ErrBox.Visible = true;
                    ErrMsg.Text = ex.Message;
                }
            }
        }

        private void BindUserTypeData()
        {
            Shuba.Business.MsStd _MstStd = new Shuba.Business.MsStd();
            List<MstStdInfo> list = _MstStd.GetListActive(Int16.Parse(ddlAppType.SelectedValue)); //_MstStd.GetList("%", 10);
            ddlUserType.DataSource = list;
            ddlUserType.DataTextField = "MstName";
            ddlUserType.DataValueField = "MstID";
            ddlUserType.DataBind();
            ddlUserType.Items.Insert(0, "- Pilih dengan tepat dan benar -");
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("branch_nip_so_list.aspx");
        }

        protected void ddlUserType_SelectedIndexChanged(object sender, EventArgs e)
        {
            string UserType = ddlUserType.SelectedValue == null ? "" : ddlUserType.SelectedValue.Trim();

            if (UserType == "TL")
                ddlAOType.SelectedIndex = 1;
            else
                ddlAOType.SelectedIndex = 0;
        }

        protected void ddlAppType_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindUserTypeData();
        }
    }
}
